<?php

namespace App\Http\Controllers\Guard\Article;

use App\Http\Controllers\Common\GuardController;
use App\Models\Article\ArticleClassify;
use App\Models\Constant\Constant;
use Illuminate\Http\Request;


class ArticleClassifyController extends GuardController {

    public function lst(Request $request) {

        if($request->has('tree')){
            $conditions = ['pid'=>0];
            $conditions['orderBy']['col'] = 'id';
            $conditions['orderBy']['sort'] = 'asc';
            $records = (new ArticleClassify())->getLst($conditions)->with('children')->get();
            $this->handleChildren($records);
            return responseSuccess($records->toArray());
        }
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',Constant::PAGE_SIZE);
        $conditions = $request->input();
        $records = (new ArticleClassify())->getLst($conditions)->paginate($pageSize,['*'],'page',$page);
        return responseSuccess($records->items(),$records->total());
    }

    public function add(Request $request) {

        try{
            $id = $request->input('id',0);
            $info = $request->input();

            ArticleClassify::updateOrCreate(compact('id'),$info);
            return responseSuccess();
        }catch(\Exception $e){
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }
    }

    public function detail(Request $request) {

        $ids = $request->input('ids',[]);
        $records = $this->getDetail(ArticleClassify::class, $ids);
        foreach ($records as $record) {
            $record->p_name = $record->getParent()->name??'顶级分类';
        }
        return responseSuccess($records->toArray());
    }

    public function del(Request $request) {
        return $this->delRecords(ArticleClassify::class, $request->input('ids',''));
    }




}
